package com.habdqn.easybuy.web.manage.product;

import cn.hutool.core.convert.impl.UUIDConverter;
import cn.hutool.core.lang.generator.UUIDGenerator;
import com.habdqn.easybuy.entity.Product;
import com.habdqn.easybuy.entity.ProductCategory;
import com.habdqn.easybuy.service.ProductService;
import com.habdqn.easybuy.service.impl.ProductCategoryServiceImpl;
import com.habdqn.easybuy.service.impl.ProductServiceImpl;
import com.habdqn.easybuy.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Xing.Jiejian
 * @date 2020/11/26 0026
 */
@WebServlet(name = "ProductAddServlet", urlPatterns = "/manage/product/add")
@MultipartConfig
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Product product = new Product();
        // 接收普通属性
        product.setName(request.getParameter("name"));
        String strCategoryId = request.getParameter("categoryId");
        if (StringUtils.isNotBlank(strCategoryId)) {
            product.setCategoryId(Integer.parseInt(strCategoryId));
        }
        String strPrice = request.getParameter("price");
        if (StringUtils.isNotBlank(strPrice)) {
            product.setPrice(Double.parseDouble(strPrice));
        }
        product.setDescription(request.getParameter("description"));
        String strStock = request.getParameter("stock");
        if (StringUtils.isNotBlank(strStock)) {
            product.setStock(Integer.parseInt(strStock));
        }

        // 处理图片上传部分
        // 接收文件对象
        Part part = request.getPart("fileName");
        if (part != null) {
            // 获取源文件名
            String cd = part.getHeader("Content-Disposition");
            // 获取原文件名 xxx.jpg
            String filename = cd.substring(cd.lastIndexOf("=") + 2, cd.length() - 1);
            if (filename.length() > 0) {
                // 获取原本文件的后缀
                String extName = filename.substring(filename.lastIndexOf("."));
                // 生成新的文件名
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String newFilename = uuid + extName;
                // 设定文件保存的路径(”/upload“),获取上传目录在服务器中的完整路径
                String savePath = request.getServletContext().getRealPath("/upload/product");
                // 将文件使用新文件名保存到服务器指定路径
                part.write(savePath + "/" + newFilename);
                product.setFileName("/upload/product" + newFilename);
            }
        }

        ProductService productService = new ProductServiceImpl();
        if (productService.insert(product).getId() != null) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<script>");
            out.println("alert('新增商品成功！');");
            out.println("location.href='" + request.getContextPath() + "/manage/product';");
            out.println("</script>");
        } else {
            request.setAttribute("errorMsg", "新增失败");
            doGet(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取所有分类
        List<ProductCategory> categories = new ProductCategoryServiceImpl().queryAll();
        request.setAttribute("categories", categories);
        request.getRequestDispatcher("/WEB-INF/manage/product/product-add.jsp").forward(request, response);
    }
}
